package vip.dexian.admin.security.handler;

import vip.dexian.admin.security.config.SecurityConfig;
import vip.dexian.common.Message;
import vip.dexian.common.utils.WebUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 认证失败错误处理
 *
 * @author 挺好的 2023年06月06日 11:18
 */
@Component ("simpleAuthenticationEntryPoint")
@Slf4j
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {

    /***
     * 认证失败。如果非ajax请求，则跳转到登录页面。否则的话标记状态码为401，由请求方自行决定要做什么操作
     * @param request
     * {@link HttpServletRequest}
     * @param response
     * {@link HttpServletResponse}
     * @param authException
     * 异常信息 。{@link org.springframework.security.core.AuthenticationException}
     * @throws java.io.IOException
     * @throws ServletException
     */
    @Override
    public void commence (HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {

        log.debug("认证失败!", authException);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // 如果不是ajax请求
        if (!WebUtils.isAjaxRequest(request)) {
            response.sendRedirect(SecurityConfig.LOGIN);
            return;
        }
        WebUtils.responseMessage(response, Message.error(HttpServletResponse.SC_UNAUTHORIZED));
    }
}
